import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login', '/login2', '/auth-redirect'] // no redirect whitelist

router.beforeEach(async(to, from, next) => {
  // start progress bar
  NProgress.start()

  // set page title
  document.title = getPageTitle(to.meta.title)

  // 确定用户是否已经登录
  const hasToken = getToken()
  // console.log(hasToken,'hastoken');
  // 有token
  if (hasToken) {
    if (to.path === '/login') {
      // 跳转到首页去
      if (store.getters.roles[0]==="auditor") {
        // router.push()
        next({ path: '/logAnalysis/auditLog'})
      }else if (store.getters.roles[0]==="manager"){
        next({ path: '/system/userManager'})
      }
      // next({ path: '/' })
      next({ path: '/' })
      NProgress.done()
    } else {
        const hasRoles = store.getters.roles && store.getters.roles.length > 0;
        console.log(hasRoles);
        // const hasGetUserInfo = store.getters.name
      if (hasRoles) {
        // console.log(store.getters.roles[0]);
        // if (store.getters.roles[0]==="auditor" && (from.path === "/login" || from.path === "/") &&  to.path != "/logAnalysis/auditLog") {
        //   // console.log(111111);
        //   router.push({ path: '/logAnalysis/auditLog'})
        //   next()
        // }else if (store.getters.roles[0]==="manager" && (from.path === "/login" || from.path === "/") && to.path != "/system/userManager" ){
        //   // console.log(222222);
        //   router.push({ path: '/system/userManager'})
        //   next()
        // }else{
          // console.log(333333);

          next()
        // }
        
      } else {
        try {
          
          // 获取用户信息
          // await store.dispatch('user/getInfo')
          // 注意:角色必须是一个对象数组! 例如: ['admin'] or ,['test','edit']
          const  { roles }  = await store.dispatch('user/getInfo');
          // // 根据角色生成可访问路由映射
          const accessRoutes = await store.dispatch('permission/generateRoutes', roles);
          // await store.dispatch('user/setRole', roles)
          // // 动态添加可访问路由
          router.addRoutes(accessRoutes);
          if (store.getters.roles[0]==="auditor" && to.path === '/') {
            // router.push()
            next({ path: '/logAnalysis/auditLog',replace: true })
          }else if (store.getters.roles[0]==="manager"  && to.path === '/'){
            next({ path: '/system/userManager',replace: true })
          }else{
            next({ ...to, replace: true });
          }
          // // 设置replace: true，这样导航就不会留下历史记录
          // next({ ...to, replace: true });
          // next()
        } catch (error) {
          // 移除令牌，重定向值登录页面
          await store.dispatch('user/resetToken') 
          Message.error(error || 'Has Error')
          next(`/login?`)
          // redirect=${to.path}
          NProgress.done()
        }
      }
    }
  } else {
    /* 没有token*/
    if (whiteList.indexOf(to.path) !== -1) {
      // 跳转到不需要token值得页面
      next()
    } else {
      // 没有访问权限的跳转至登录页去
      next(`/login?`)
      // redirect=${to.path}
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // 进度条完成
  NProgress.done()
})
